import Immutable from 'immutable'
import {
	TOKEN,
} from '../constants'
import * as Utils from '../utils'

let initialState = Immutable.fromJS({
	hasLogin: false,
	errorMsg: '',
})

export default function loginReducer(state = initialState, action) {
	let operation = {
		LOGIN_SUCCESS: () => {
			Utils.setItem(TOKEN, action.response)
			return state.merge({
				hasLogin: true,
			})
		},
		LOGIN_FAILED: () =>
			state.merge({
				errorCode: action.errorCode,
				errorMsg: action.errorMsg,
			}),
		LOGOUT: () =>
			state.merge({
				hasLogin: false,
				errorCode: null,
				errorMsg: null,
			}),
		CLEAR_ERRMSG: () =>
			state.merge({
				errorCode: null,
				errorMsg: null,
			}),
	}

	if (operation[action.type]) {
		return operation[action.type]()
	}

	return state
}